<?php
/**
 * Desc:
 * User: zdb
 * Date: 2023/6/5
 * Time: 14:43
 */

namespace app\util;
use app\api\service\log\ErrorLogService;
use app\api\service\system\SystemSettingService;
use think\facade\Db;

class CommonUtil
{
    CONST ARR_WEEK_OPTION = [
        1 => '周一',
        2 => '周二',
        3 => '周三',
        4 => '周四',
        5 => '周五',
        6 => '周六',
        7 => '周日',
    ];
    public static function getPaginationData($data, $total, $pageIndex = 1, $pageSize = 30)
    {
        $pagination = [
            "page" => $pageIndex,
            "limit" => $pageSize,
            "total" => $total
        ];
        $finalData = [
            "pagination" => $pagination,
            "list" => $data
        ];
        return $finalData;
    }


    public static function getProjectPath()
    {
        $curDirPath = __DIR__;
        $curDirPath = str_replace('\\', '/', $curDirPath);
        $projectPath = substr($curDirPath, 0, strpos($curDirPath, 'memory') + 6);
        return $projectPath;
    }

    /**
     * @param $string
     * @param $type
     */
    public static function validateStringFormat($string, $type)
    {

    }

    /**
     * [is_mobile 判断设备是PC还是移动端]
     * @return boolean [description]
     */
    public static function isMobileDevice()
    {

        $flag = false;
        if (isset($_SESSION['device_style'])) {
            if (0 == $_SESSION['device_style']) {
                $flag = true;
            }
        } else {
            $_SESSION['device_style'] = 1;
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $mobile_browser = array(
                "mqqbrowser", //手机QQ浏览器
                "opera mobi", //手机opera
                "juc", "iuc",//uc浏览器
                "fennec", "ios", "applewebKit/420", "applewebkit/525", "applewebkit/532", "ipad", "iphone", "ipaq", "ipod",
                "iemobile", "windows ce",//windows phone
                "240×320", "480×640", "acer", "android", "anywhereyougo.com", "asus", "audio", "blackberry", "blazer", "coolpad", "dopod", "etouch", "hitachi", "htc", "huawei", "jbrowser", "lenovo", "lg", "lg-", "lge-", "lge", "mobi", "moto", "nokia", "phone", "samsung", "sony", "symbian", "tablet", "tianyu", "wap", "xda", "xde", "zte"
            );

            foreach ($mobile_browser as $device) {
                if (stristr($user_agent, $device)) {
                    $flag = true;
                    $_SESSION['device_style'] = 0;
                    break;
                }
            }
        }

        return $flag;
    }

    public static function getUrlPrefix()
    {
        return 'http://' . config('app.app_host') . "/";
    }


    /**
     * Desc: 解析Ip的归属地
     * Datetime: 2024/2/2 16:15 by zdb
     */
    public static function resolveIpPosition($visitIp)
    {
//        $ak = "tmM5YvWq0SDFMb5nNIaUzetMD76ugURB";
//        $url = "https://api.map.baidu.com/location/ip?ak=".$ak."&ip=".$visitIp;
//        $res = get_url_content($url);
//        if( 1 == $res['status'] ){
//            //如果异常，可能是国外ip，换个接口查询
//            //https://ipbase.com/pricing/
//            $url = "https://whois.pconline.com.cn/ipJson.jsp?ip=".$visitIp."&json=true";
//            $res = get_url_content($url);
//
//            $logdata['province'] = $check_res['location'];
//        }else{
//            $logdata['province'] = $check_res['content']['address_detail']['province'];
//            $logdata['city'] = $check_res['content']['address_detail']['city'];
//            $logdata['street'] = $check_res['content']['address_detail']['street'];
//            $logdata['district'] = $check_res['content']['address_detail']['province'];
//            $logdata['street_number'] = $check_res['content']['address_detail']['street_number'];
//            $logdata['longititude'] = $check_res['content']['point']['x'];
//            $logdata['latitude'] = $check_res['content']['point']['y'];
//        }
//        return json_decode($res, true);
    }

    public static function covertUnderlineToUpperCamel($str)
    {
        $strWithBlank = str_replace('_', ' ', $str);
        return str_replace(' ', '', ucwords($strWithBlank));
    }

    public static function covertUnderlineToLowerCamel($str)
    {
        $strWithBlank = str_replace('_', ' ', $str);
        $str = str_replace(' ', '', ucwords($strWithBlank));
        return lcfirst($str);
    }

    public static function addErrorLog($controllerName, $actionName, $message)
    {
        $service = new ErrorLogService();
        $data = [
            'controller_name' => strpos($controllerName, '\\') ? basename($controllerName):$controllerName,
            'action_name' => $actionName,
            'error_message' => $message,
        ];
        return $service->createRow($data);
    }

    /**
     * @param $oldData
     * @param $newData
     * @param $arrFieldText
     * @param array $optionData
     * @return array
     */
    public static function getChangeData($oldData, $newData,$arrFieldText, $optionData = [], $primaryField = '')
    {
        $arrKeys = array_keys($oldData);
        $relateField = [];  //修改的字段
        $updateContent = [];
        $message    = [];
        $yesOrNo    = [0 => 'No', 1 => 'Yes'];
        $statusText = [1 => '启用', 2 => '禁用', 0=>'删除'];
        if($primaryField){
            $message[]  = "[<b>".$arrFieldText[$primaryField]."</b>]:".$oldData[$primaryField];
        }
        foreach($arrKeys as $field){
            if(isset($newData[$field]) && $oldData[$field] != $newData[$field]){
                if($field == $primaryField){
                    unset($message[0]);
                }
                $relateField[] = $field;
                $updateContent[$field] = array('old' => $oldData[$field], 'new' => $newData[$field]);
                $fieldText = isset($arrFieldText[$field]) ? $arrFieldText[$field]:$field;
                if(0 === stripos($field, "is_") && isset($yesOrNo[$oldData[$field]]) && isset($yesOrNo[$newData[$field]])){
                    $message[] = "[<b>$fieldText</b>]:".$yesOrNo[$oldData[$field]]."->".$yesOrNo[$newData[$field]];
                }else if('status' == $field){
                    $message[] = "[<b>$fieldText</b>]:".$statusText[$oldData[$field]]."->".$statusText[$newData[$field]];
                }else if(in_array($field, array_keys($optionData))){
                    $textArr = $optionData[$field];
                    $valueOld = $textArr[$oldData[$field]] ?? '';
                    $valueNew = $textArr[$newData[$field]] ?? '';
                    $message[] = "[<b>$fieldText</b>]:".$valueOld."->".$valueNew;
                }else{
                    $valueOld = is_array($oldData[$field]) ? implode(",",$oldData[$field]):$oldData[$field];
                    $valueNew = is_array($newData[$field]) ? implode(",",$newData[$field]):$newData[$field];
                    $message[] = "[<b>$fieldText</b>]:".$valueOld."->".$valueNew;
                }
            }
        }
        return ['update_info' => implode(" ", $message),
            'change_field'  => $relateField];
    }

    public static function getDataInsertMessage($newData, $arrFieldText)
    {
        $message = [];
        $statusText = [1 => '启用', 2 => '禁用', 0=>'删除'];
        foreach($arrFieldText as $field => $fieldText){
            if('status' == $field){
                $fieldDataInt = $newData[$field] ?? 1;
                $fieldData = $statusText[$fieldDataInt];
            }else{
                $fieldData = $newData[$field] ?? '';
            }
            if('' !== $fieldData){
                $message[] = "[<b>$fieldText</b>]:".$fieldData;
            }
        }
        return implode(", ", $message);
    }

    /**
     * 默认删除单个的日志
     * @param $deleteData
     * @param $arrField
     * @param bool $isSingle
     * @return string
     */
    public static function getDataDeleteMessage($deleteData, $arrField, $isSingle = true, $arrRecordField = array())
    {
        if($isSingle){
            $message = [];
            $statusText = [1 => '启用', 2 => '禁用', 0=>'删除'];
            foreach($arrField as $field => $fieldText){
                if('status' == $field){
                    $fieldDataInt = $deleteData[$field] ?? 1;
                    $fieldData = $statusText[$fieldDataInt];
                }else{
                    $fieldData = $deleteData[$field] ?? '';
                }
                if('' !== $fieldData){
                    $message[] = "[<b>$fieldText</b>]:".$fieldData;
                }
            }
            return implode(", ", $message);
        }else{
            $message = [];
            foreach($deleteData as $index => $item){
                $count = $index+1;
                $info = "<b>($count)</b>";
                $fieldData = [];
                foreach($arrRecordField as $field){
                    $fieldData[] = $item[$field] ?? '';
                }
                $info .= implode(",", $fieldData);
                $message[] = $info;
            }
            return implode("; ", $message);
        }
    }

    public static function getSystemSetting($symbol){
        $service = new SystemSettingService();
        $res = $service->getSystemSettingInfoByCondition(['symbol'=>$symbol, 'status'=>1]);
        if($res && 'numeric' == $res['data_type']){
            return $res['content'];
        }else{
            return isset($res['content']) ? $res['content']:'';
        }
    }

    /**
     * D:哪一天
     * T:哪个钟点
     * W:附带后缀
     * @return string
     */
    public static function makeDeviceKey()
    {
        $nowTime = DateUtil::getCurrentDatetime("Ymd");
        $nowTime .= "T";
        $nowTime .= DateUtil::getCurrentDatetime("Hi");
        $arrHaystack = [1, 2, 3, 4, 5, 6, 7, 8, 9,
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        $arrRandIndex = array_rand($arrHaystack, 6);
        $randStr = '';
        foreach ($arrRandIndex as $index) {
            $randStr .= $arrHaystack[$index];
        }
        return "D".$nowTime.'W'.$randStr;
    }


    /**
     * Desc: 判断模板类型
     * 返回数组形式，方便扩展
     * @param $templateNo
     * @return int[]|void
     * Datetime: 2024/6/27 9:05 by zdb
     */
    public static function judgeTemplateStyle($templateNo){
        $templateNo = strtoupper($templateNo);
        if('T1' == $templateNo){
            return ['task' => 1, 'person' => 0];
        }else if('T2' == $templateNo){
            return ['task' => 0, 'person' => 1];
        }
    }

    /**
     * Desc: 获取异常消息
     * @param $e
     * Datetime: 2024/8/12 14:49 by zdb
     */
    public static function getExceptionMessage($e)
    {
        $errorMessage = $e->getMessage()."(Line:".$e->getLine()." in ".$e->getFile().")";
        return $errorMessage;
    }

    public static function getDictionarySubListByCode($code){
        $list = Db::table('yj_dictionary_sub')->alias('a')
            ->leftJoin('yj_dictionary d', 'd.id = a.dictionary_id')
            ->where('d.dictionary_code', '=', $code)
            ->where('a.status', '=', 1)
            ->field('a.dictionary_id,a.sub_name,a.sub_value')
            ->select()
            ->toArray();
        return $list;
    }

    /**
     * Desc: 生成唯一性标识码
     * uniqid 13位
     * @param $prefix
     * Datetime: 2024/12/13 11:15 by zdb
     */
    public static function makeUniqueCode($prefix, $randomNum = 5, $boolUpperCase = false)
    {
        $code = uniqid($prefix);
        $arrHaystack = [1, 2, 3, 4, 5, 6, 7, 8, 9,
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        $arrRandIndex = array_rand($arrHaystack, $randomNum);
        $randomPrefix = "";
        foreach ($arrRandIndex as $index) {
            $randomPrefix .= $arrHaystack[$index];
        }
        $code = $randomPrefix.$code;
        if($boolUpperCase){
            $code = strtoupper($code);
        }
        return $code;
    }
}
